<template>
  <div class="devices-index">
    <div class="offline mask" v-show="showOfflineModal" transition="fromTop">
      <div class="offline-tips">
        <span>设备已离线！</span>
      </div>
    </div>
    <!-- 设备列表 -->
    <div class="devices-box ul" v-show="deviceList.length">
      <div class="list device" v-for="device in deviceList" v-ev:tap.stop="[enterControlPage,device]">
        <div class="icon-box">
          <div class="icon device-icon" :class="device.type" :class="{'warn': device.warn, 'offline': !device.online}">
            <div class="warn-mask" v-show="device.warn">
              <span class="danger"></span>
            </div>
            <div class="offline-mask" v-show="!device.online">
              <span class="question">?</span>
            </div>
          </div>
        </div>
        <div class="label device-name">{{device.name}}</div>
      </div>
    </div>
    <!-- 无设备提示 -->
    <div class="no-devices" v-show="!isLoading && !deviceList.length">
      <warn :title="'暂无设备'" :tips="'请点击发现-扫描二维码进行添加设备'"></warn>
    </div>
    <!-- ios页面跳转强制刷新title -->
    <iframe v-if="showIframe" src="./static/logo.png" style="display:none"></iframe>
  </div>
</template>

<script>
  var Range = require('../../../shared/components/range.vue')
  // var Header = require('../../../shared/components/header.vue')
  var Warn = require('../../../shared/components/warn.vue')
  // import SDK from '../../helpers/sdk'
  import {getDeviceInfo} from '../../api/index'
  console.log(getDeviceInfo)
  import { globalMixins } from '../../mixins'

  export default {
    mixins: [globalMixins],

    components: {
      'warn': Warn,
      'v-range': Range
    },

    data () {
      return {
        // 显示设备离线浮层标志位
        showOfflineModal: false,
        // 设备列表
        deviceList: [
          // {
          //   id: '11111',
          //   name: '办公室1',
          //   type: 'office-room',
          //   warn: false,
          //   online: false
          // },
          // {
          //   id: '22222',
          //   name: '办公室2',
          //   type: 'office-room',
          //   warn: true,
          //   online: true
          // }
        ],
        isLoading: false
      }
    },

    route: {
      data () {
        this.setTitle('我的设备')
      }
    },
    ready () {
      var self = this
      if (window.devices) {
        this.devicesInit(window.devices)
      } else {
        this.showLoading('正在搜索设备')
        this.isLoading = true
        window.devicesReady = function (devices) {
          self.hideLoading()
          self.isLoading = false
          if (devices) {
            self.devicesInit(devices)
          }
        }
      }
      if (this.debug) {
        this.hideLoading()
      }
    },
    methods: {
      /**
       * 长按设备进入控制设备页面
       * @param  {[type]} device [description]
       * @return {[type]}        [description]
       */
      enterControlPage (device, e) {
        if (device.online) {
          this.setTitle(device.name)
          this.goTo('/devices/' + device.id)
        } else {
          this.showOffline()
        }
      },
      showOffline () {
        this.showOfflineModal = true
        setTimeout(() => {
          this.showOfflineModal = false
        }, 2000)
      },
      devicesInit (devices) {
        var self = this
        devices.forEach(function (device) {
          device.on('data', function (data) {
            self.dispatchDeviceDate(device, data)
          })
          .on('disconnect', function (data) {
            self.showMessage('设备 ' + device.id + '断开')
          })
          .on('connect', function (data) { // connect事件触发表示当前设备实例连接上了云智易服务器。
            console.log(data)
          })
          .on('statuschange', function (status) { // status=1 表示设备在线，status=0表示设备离线 status=其他 发生错误
            self.deviceList.map((item) => {
              if (item.id === device.id) {
                item.online = status - 0
                device.online = item.online
              }
            })
          })

          var obj = {
            id: device.id,
            name: device.name || device.id,
            type: 'office-room',
            warn: false,
            online: device.online
          }

          if (!device.datapoint) {
            device.datapoint = {}
          }

          if (device.datapoint[device.id]) {
            console.log(device.datapoint[device.id])
            var list = device.datapoint[device.id]
            obj.warn = self.saveDataProcess(list)
          } else {
            device.datapoint[device.id] = new Array(7)
          }
          console.log(obj)
          self.deviceList.push(obj)

          self.getDeviceDetail(device)
        })

        self.hideLoading('')
        this.isLoading = false
      },
      dispatchDeviceDate (device, data) {
        var list = data.data.datapoint
        if (!list || list.length <= 0) {
          return
        }

        // 将设备当前数据直接绑定在设备对象上
        if (!device.datapoint[device.id]) {
          device.datapoint[device.id] = new Array(7)
        }

        // 是否报警
        var warn = this.dataProcess(list, device)
        console.log(warn)

        // 找出devicelist对应的设备
        var deviceIndex = 0
        for (var i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i].id === device.id) {
            deviceIndex = i
          }
        }

        // console.log(this.deviceList)
        // if (this.deviceList[deviceIndex].warn === warn) {
        //   return
        // }

        var obj = {
          id: device.id,
          name: device.name || device.id,
          type: 'office-room',
          warn: warn,
          online: this.deviceList[deviceIndex].online
        }
        console.log(obj)
        this.deviceList.$set(deviceIndex, obj)
      },

      saveDataProcess (list) {
        console.log('index------------------')
        console.log(list)
        var warn = false
        for (var i = 0; i < list.length; i++) {
          switch (i) {
            case 0: // 烟雾
              if (list[i] === true) {
                warn = true
              }
              break
            case 1: // 温度
              if (list[3]) {
                if (list[i] >= list[3]) {
                  warn = true
                }
              }
              break
            case 2: // 有毒气体
              if (list[4]) {
                if (list[i] >= list[4]) {
                  warn = true
                }
              }
              break
            // 不存储温度和有毒气体设置数据。以下2个数据端点用来发送数据
            case 3: // 温度设置
              break
            case 4: // 有毒气体设置
              break
            /* 报警信息不做处理, app已知设备告警阈值，只根据设备状态数值判断 */
            case 5: // 温度报警
              break
            case 6: // 有毒气体报警
              break
            default:
              break
          }
        }

        return warn
      },

      // 返回值表示是否触发告警
      dataProcess (list, device) {
        console.log(list)
        var warn = false
        list.forEach((item) => {
          if (!device) {
            return
          }
          if (!device.datapoint) {
            device.datapoint = {}
          }
          if (device.datapoint[device.id]) {
            device.datapoint[device.id][item.index] = item.value
          } else {
            device.datapoint[device.id] = new Array(7)
            device.datapoint[device.id][item.index] = item.value
          }
          switch (item.index) {
            case 0: // 烟雾
              if (item.value === true) {
                warn = true
              }
              break
            case 1: // 温度
              console.log(list[3].value)
              console.log(item.value)
              if (list[3].value) {
                if (item.value >= list[3].value) {
                  warn = true
                }
              }
              break
            case 2: // 有毒气体
              console.log(list[4].value)
              console.log(item.value)
              if (list[4].value) {
                if (item.value >= list[4].value) {
                  warn = true
                }
              }
              break
            // 不存储温度和有毒气体设置数据。以下2个数据端点用来发送数据
            case 3: // 温度设置
              break
            case 4: // 有毒气体设置
              break
            /* 报警信息不做处理, app已知设备告警阈值，只根据设备状态数值判断 */
            case 5: // 温度报警
              break
            case 6: // 有毒气体报警
              break
            default:
              break
          }
        })

        return warn
      },
      getDeviceDetail (device) {
        getDeviceInfo(device.id).then((res) => {
          if (res.status === 200 && res.data.device_name && res.data.device_name !== '') {
            // 找出devicelist对应的设备
            for (var i = 0; i < this.deviceList.length; i++) {
              if (this.deviceList[i].id === device.id) {
                this.deviceList[i].name = res.data.device_name
              }
            }

            device.name = res.data.device_name
            console.log(device)
          }
        }).catch((res) => {
          console.log(res)
        })
      }
    }
  }
</script>

<style lang="stylus">
  @import '../../../shared/assets/style/common'

  .offline
    .offline-tips
      width 100%
      height 1.2rem
      line-height 1.2rem
      color #fff
      background rgba(255,0,0,0.8)
      text-align center
      font-size 0.4rem
  .mask
    width 100%
    height 100%
    position absolute
    top 0
    left 0
    z-index 9
  .devices-index
    .devices-box
      height 85%
      min-height 10rem
      box-sizing border-box
      margin-top 1rem
    .no-devices
      width 100%
      height 100%
      box-sizing border-box
  .ul
    width 100%
    height 100%
    clearfix()
    overflow-y auto
    -webkit-overflow-scrolling touch
    .list
      width 33.3%
      height 4rem
      float left
      .icon-box
        width 2.5rem
        height 2.5rem
        margin 0 auto
        border-radius 3rem
        background #fff
        padding 0.08rem 0.08rem
        box-sizing border-box
        position relative
        box-shadow 0 0.1rem 0.2rem rgba(0,0,0,0.3)
        .icon
          width 100%
          height 100%
          border-radius 3rem
          background-size 100% auto
          position relative
        .warn-mask
        .offline-mask
          width 100%
          height 100%
          border-radius 3rem
          background rgba(255,0,0,0.44)
          position absolute
          top 0
          left 0
          text-align center
          line-height 2.1rem
          font-size 0.5rem
          padding 18%
          box-sizing border-box
          .danger
            display block
            width 100%
            height 100%
            background-size 100%
            background-position center
        .offline-mask
          background rgba(0,0,0,0.66)
          line-height 1.6rem
          .question
            font-size 1.5rem
      .label
        height 1rem
        line-height 1rem
        text-align center
        color #fff
        font-size 0.4rem
        text-shadow 0.1rem 0.1rem 0.2rem rgba(0,0,0,0.6)
</style>
